package com.jacars.biz.user.dao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jacars.biz.user.dao.mapper.JsptMenuMapper;
import com.jacars.biz.user.dao.model.JsptRoleMenu;
import com.jacars.biz.user.dao.service.JsptMenuService;
import com.jacars.biz.user.dao.service.JsptRoleMenuService;
import com.jacars.common.model.JsptMenu;
import com.jacars.common.service.impl.SuperServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author 作者 owen E-mail: 624191343@qq.com
 */
@Slf4j
@Service
public class JsptMenuServiceImpl extends SuperServiceImpl<JsptMenuMapper, JsptMenu> implements JsptMenuService {
    @Resource
    private JsptRoleMenuService roleMenuService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void setMenuToRole(Long roleId, Set<Long> menuIds) {
        roleMenuService.delete(roleId, null);

        if (!CollectionUtils.isEmpty(menuIds)) {
            List<JsptRoleMenu> roleMenus = new ArrayList<>(menuIds.size());
            menuIds.forEach(menuId -> roleMenus.add(new JsptRoleMenu(roleId, menuId)));
            roleMenuService.saveBatch(roleMenus);
        }
    }

    /**
     * 角色菜单列表
     *
     * @param roleIds
     * @return
     */
    @Override
    public List<JsptMenu> findByRoles(Set<Long> roleIds) {
        return roleMenuService.findMenusByRoleIds(roleIds, null);
    }

    /**
     * 角色菜单列表
     *
     * @param roleIds 角色ids
     * @param roleIds 是否菜单
     * @return
     */
    @Override
    public List<JsptMenu> findByRoles(Set<Long> roleIds, Integer type) {
        return roleMenuService.findMenusByRoleIds(roleIds, type);
    }

    @Override
    public List<JsptMenu> findByRoleCodes(Set<String> roleCodes, Integer type) {
        return roleMenuService.findMenusByRoleCodes(roleCodes, type);
    }

    @Override
    public List<JsptMenu> buttons(Set<String> roleCodes, Integer type) {
        return roleMenuService.findMenusByRoleCodes(roleCodes, type);
    }


    @Override
    public JsptMenu detail(String id) {
        JsptMenu byId = this.getById(id);
        return byId;
    }

    /**
     * 查询所有菜单
     */
    @Override
    public List<JsptMenu> findAll() {
        return baseMapper.selectList(
                new QueryWrapper<JsptMenu>().orderByAsc("sort")
        );
    }

    /**
     * 查询所有一级菜单
     */
    @Override
    public List<JsptMenu> findOnes() {
        return baseMapper.selectList(
                new QueryWrapper<JsptMenu>()
                        .eq("parent_id", -1)
                        .orderByAsc("sort")
        );
    }
}
